﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Isha.Services.Infrastructure;
using Isha.Entities;
using Isha.Repositories.Infrastructure;
using Isha.Data.Infrastructure;
using System.Web.Mvc;
using Isha.Repositories;

namespace Isha.Services
{
    internal class ContentTypeService : ServiceBase, IContentTypeService
    {
        public ContentTypeService()
        {
            Initialize(null, null);
        }

        public ContentTypeService(IContentTypeRepository contenttypeRepository, IUnitOfWork unitOfWork)            
        {
            Initialize(contenttypeRepository, unitOfWork);
        }

        public IContentTypeRepository ContentTypeRepository { get; private set; }

        public IUnitOfWork UnitOfWork { get; private set; }

        public void Initialize(IContentTypeRepository contenttypeRepository, IUnitOfWork unitOfWork)
        {
            ContentTypeRepository = (contenttypeRepository ?? DependencyResolver.Current.GetService<IContentTypeRepository>());
            UnitOfWork = (unitOfWork ?? DependencyResolver.Current.GetService<IUnitOfWork>());
        }

        public IEnumerable<ContentType> GetContentTypes()
        {
            var contenttypes = ContentTypeRepository.GetMany(p => p.IsPublic == true);
            return contenttypes;
        }

        public ContentType GetContentType(long id)
        {
            var contenttype = ContentTypeRepository.Find(id);
            return contenttype;
        }

        public void CreateContentType(ContentType contenttype)
        {
            ContentTypeRepository.Add(contenttype);
            UnitOfWork.Commit();
        }

        public void DeleteContentType(long id)
        {
            ContentTypeRepository.Delete(id);
            UnitOfWork.Commit();
        }

        public override string ToString()
        {
            string contenttypes = string.Empty;

            foreach (var item in GetContentTypes())
            {
                contenttypes += item.Title + "|";
            }
            return contenttypes.TrimEnd('|');
        }

        public ContentType GetContentType(string title)
        {
            var contenttype = ContentTypeRepository.Find(p => p.Title == title);
            return contenttype;
        }       
    }
}
